<!-- 病虫害检测页面 -->
<template>
	
	<!-- 病虫害检测 -->
	<view >
		<uni-card title="病虫害检测"  sub-title="D8602032700"  extra="额外信息" :thumbnail="avatar">
			<view class="modechooose">
				<text class="uni-body">未激活</text>
				<text class="uni-body">影子模式</text>
			</view>
		</uni-card>
	</view>
	
	<!-- 土壤的相关数据 -->
	<view class="datalang">
		<uni-segmented-control :current="current" :values="itemsturang" @clickItem="onClickItem" styleType="text" activeColor="#4cd964"></uni-segmented-control>
		        <view class="content">
					
		            <view v-if="current === 0">
		                <view>
		                    <uni-card :is-shadow="false">
		                         <view class="uni-list-cell uni-list-cell-pd">
		                            <view class="uni-list-cell-db">您有新的预警消息待查收！</view>
		                        </view>
		                    </uni-card>
		                    <view class="cu-timeline">
		                        <template v-for="(item, index) in warningMessages" :key="index">
		                            <view v-if="item.date" class="cu-time" style="white-space: nowrap; padding: 5px;">{{ item.date }}</view>
		                            <view class="cu-item" :class="item.type">
		                                <view class="shadow-blur content">
		                                    <view class="cu-item">
		                                        <view class="content">
		                                            <view class="cu-capsule radius">
		                                                <view :class="['cu-tag', item.type === 'warning' ? 'bg-red' : 'bg-green']">{{ item.time.period }}</view>
		                                                <view :class="['cu-tag', item.type === 'warning' ? 'line-red' : 'line-green']">{{ item.time.hour }}</view>
		                                            </view>
		                                        </view>
		                                        <view class="margin-top">
		                                            <text  style="font-size: 25rpx;">{{ item.message }}</text>
		                                        </view>
												<!-- 添加图片显示 -->
												<view class="cu-item-image">
												    <image :src="item.imageUrl" mode="aspectFit"></image>
												</view>
		                                    </view>
		                                </view>
		                            </view>
		                        </template>
		                    </view>
		                </view>
		            </view>
					
					<view v-if="current === 1">
						<view>
							<uni-card :is-shadow="false" >
								<view class="uni-list-cell uni-list-cell-pd">
									<view class="uni-list-cell-db">是否开启实时数据</view>
									<switch checked />
								</view>
							</uni-card>
							
							<!-- 数据采集内容 -->
							<view class="data-list">
					            <template v-for="(item, index) in pestDataList" :key="item.id">
							        <view class="data-item">
							            <view class="data-item-header">
							                <view class="cu-capsule radius">
							                    <view class="cu-tag bg-cyan">{{ item.time.period }}</view>
							                    <view class="cu-tag line-cyan">{{ item.time.hour }}</view>
							                </view>
							                <view class="data-item-date">
							                    {{ item.date }}
							                </view>
							            </view>
							            <view class="data-item-image">
							                <image :src="item.image" class="img-size" mode="aspectFill"></image>
							            </view>
							        </view>
							    </template>
							</view>
						</view>
					</view>
					
		            <view v-if="current === 2">
		                设备控制
		            </view>
					
		            <view v-if="current === 3">
		                设备日志
		            </view>
					
					<view v-if="current === 4">
						<view class="charts-box">
						    <qiun-data-charts 
						      type="line"
						      :opts="optsPestWeekData"
						      :chartData="chartDataPestWeekData"
						    />
						</view>
						<view class="charts-box">
						    <qiun-data-charts 
						      type="line"
						      :opts="optsPestMonthData"
						      :chartData="chartDataPestMonthData"
						    />
						</view>
					</view>
					
		        </view>
					
	</view>
	
	
	
</template>

<script setup>
import {ref} from "vue"
import { getDeviceListByHouseID } from "@/api/duorou/dapengDeviceBind";
import { getAllPestDataList } from "@/api/duorou/pestidentification";
import { API_BASE_URL } from "@/env_config.js"
import { getPestDataByWeek,getPestDataByMonth } from "@/api/duorou/pestidentification";
import { onLoad } from '@dcloudio/uni-app'
import request from '@/utils/request'

const baseUrl=API_BASE_URL ;
const deviceCategoryId=ref(null)
const greenhouseId=ref(null)
onLoad((options)=>{
	console.log("获取到的页面参数",options);
	deviceCategoryId.value=options.deviceCategoryId;
	greenhouseId.value=options.greenhouseId;
	getAllPestMeasureData();
	getWarningMessages();
})

const avatar = ref("../../../../static/images/pest.png");

//分段器
const itemsturang = ref(['预警消息', '数据采集', '设备控制', '设备日志','数据分析'])
const current =ref(0)
function onClickItem(e){
	if (current.value != e.currentIndex) {
	        current.value = e.currentIndex;
			getPestPageData(current.value)
	}
}

const warningMessages = ref([]);

const getMessageImageUrl = (message) => {
    const params = message.messageSpecialInfo
      .replace(/\{|}/g, '')
      .split(', ')
      .reduce((acc, item) => {
            const [key, value] = item.split('=');
            acc[key] = value;
            return acc;
        }, {});
    // 检查 params.url 是否存在且不为空
    if (!params.url) {
        return "图片加载失败";
    }
    return params.url;
};

/**
* 获取预警消息
*/
async function getWarningMessages() {
    try {
		const res = await request({
			url: '/admin/iotDeviceMessage/page', 
			method: 'GET',
			data: {
				current: 1,
				size: 10,
			},
		});
		if (res.statusCode === 200) {
			const records = res.data.data.records;
			const filteredRecords = records.filter(item => item.messageType === 'BINGCHONG_ALARM');
			const formattedMessages = filteredRecords.map(item => {
				const [date, time] = item.createTime.split(' ');
				const [year, month, day] = date.split('-');
				const [hour, minute] = time.split(':');
				const period = getPeriod(hour);
				return {
					fullTime: `${year}-${month}-${day} ${hour}:${minute}`,
					date: `${year}-${month}-${day}`,
					time: { period, hour: `${hour}:${minute}` },
					type: 'warning',
					message: item.messageDescribe,
					imageUrl: baseUrl+ getMessageImageUrl(item) ,
				};
			});
			
			// 新增排序逻辑：按日期倒序排列
			formattedMessages.sort((a, b) => {
				return new Date(b.fullTime) - new Date(a.fullTime);  // 降序排列
			});
			
			warningMessages.value = formattedMessages;
			console.log("收到的消息：", warningMessages);
		} else {
			console.error('请求失败:', res.errMsg);
		}
	} catch (error) {
		console.error('请求出错:', error);
	}
}

/**
 * 获取数据采集
 */
const pestDataList = ref([]);
//设备信息
const iotDevice=ref(null) 
/**
 * 获取病虫害设备中的测量数据
 */
function getAllPestMeasureData(){
	getDeviceListByHouseID({greenhouseId:greenhouseId.value,deviceCategoryId:deviceCategoryId.value,current:1,size:1})
	.then(res=>{
		iotDevice.value=res.data.data[0];
		console.log("获取所有设备值",iotDevice.value)
		getAllPestDataList({current:1,size:10,iotDeviceId:iotDevice.value.id})
		.then(res=>{
			console.log("获取所有病虫害测量数据",res)
			
			const pestMeasureList = res.data.data.records;
			pestMeasureList.map(item => {
				const [date, time] = item.updateTime.split(' ');
				const [year, month, day] = date.split('-');
				const [hour, minute] = time.split(':');
				const period = getPeriod(hour);
				const image = item.detectedFileName ? `${API_BASE_URL}${item.detectedFileName}` : '';
				item.date = `${month}-${day}`;
				item.time = { period, hour: `${hour}:${minute}` };
				item.type = "text-grey";
				item.message = item.predictStatus;
				item.image = image;
			});
			pestDataList.value=pestMeasureList;
		})
	})
}
//判断出现病虫害的时间是上午、下午还是晚上
function getPeriod(hour) {
	const hourInt = parseInt(hour, 10);
	if (hourInt >= 0 && hourInt < 12) {
		return "上午";
	} else if (hourInt >= 12 && hourInt < 18) {
		return "下午";
	} else {
		return "晚上";
	}
}


function getPestPageData(current){
	if(current===3){
		getPestWeekData();
		getPestMonthData()
	}
}
/**
 * 获取病虫害一周的检测情况
 */
function getPestWeekData(){
	getPestDataByWeek({iotDeviceId:iotDevice.value.id})
	.then(res=>{
		const dataList=res.data.data
		let xData=dataList.map(item=>{
			return item.xdata.substring(5);
		}) 
		let yData=dataList.map(item=>{
			return item.ydata
		})
		chartDataPestWeekData.value.categories=xData
		chartDataPestWeekData.value.series[0]={name:"病虫害统计--周",data:yData}
	})
}
/**
 * 获取病虫害一月的检测情况
 */
function getPestMonthData(){
	getPestDataByMonth({iotDeviceId:iotDevice.value.id})
	.then(res=>{
		const dataList=res.data.data
		
		// 对数据进行排序，确保按时间顺序排列
		dataList.sort((a, b) => new Date(a.xdata) - new Date(b.xdata));
		
		// 只保留最近6个月的数据
		const now = new Date();
		const sixMonthsAgo = new Date(now.setMonth(now.getMonth() - 6));
		const filteredDataList = dataList.filter(item => new Date(item.xdata) >= sixMonthsAgo);
		
		let xData=filteredDataList.map(item=>{
			return item.xdata.substring(2);
		}) 
		let yData=filteredDataList.map(item=>{
			return item.ydata
		})
		chartDataPestMonthData.value.categories=xData
		chartDataPestMonthData.value.series[0]={name:"病虫害统计--月",data:yData}
	})
}

//数据分析的两个图
//病虫害统计--周
const chartDataPestWeekData = ref({
	categories:[],
	series:[]
})
const optsPestWeekData = ref({
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [15,10,0,15],
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow"
          }
        }
      }
)
//病虫害统计--月
const chartDataPestMonthData = ref({
	categories:[],
	series:[]
})
const optsPestMonthData = ref({
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [15,10,0,15],
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow"
          }
        }
      }
)
</script>

<style lang="scss">
.uni-card {
		.uni-card__header{
			margin-top: 20rpx;
			.uni-card__header-content{
				margin-left: 20rpx;
			}
		}
	}
	.modechooose{
		display: flex;
		flex-direction: row;
		font-size: 13px;
		margin-left: 70rpx;
		.uni-body{
			margin-left: 30rpx;
		}
		
	}
	.datalang{
		margin-top: 30rpx;
	}
	.uni-list-cell {
		position: relative;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		
		.uni-list-cell-pd {
			padding: 22rpx 30rpx;
		}
		.uni-list-cell-db {
			margin-left: 20rpx;
			flex: 1;
		}
	}
	.datadetail{
		display: flex;
		flex-direction: row;
		.datadetail-small{
			display: flex;
			flex-direction: row;
			.uni-body1{
				// margin-left: 10rpx;
			}
			.uni-body2{
				display: flex;
				margin-left: auto;
			}
		}
	}
	
	.charts-box {
	    width: 100%;
	    height:  500rpx;
		margin-top: 15rpx;
	}
	
	.img-size{
		height: 300rpx;
	}
	.warning-text {
	  color: red;
	  // font-weight: bold;
	  
	}

.cu-timeline {
	margin-left: 20rpx;
	margin-right: 20rpx;
	border-radius: 5rpx;
}

.cu-item-image {
	width: 100%;
	height: 300rpx;
	border-radius: 10rpx;
	overflow: hidden;
	margin-top: 20rpx;
}

.data-list {
    padding: 20rpx;
}

.data-item {
    background-color: #fff;
    border-radius: 10rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
    padding: 30rpx;
	margin: 0 5rpx 40rpx 5rpx;
    // margin-bottom: 40rpx;
}

.data-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
}

.data-item-date {
    font-size: 14px;
    color: #666;
}

.data-item-image {
    width: 100%;
    height: 500rpx;
    border-radius: 10rpx;
    overflow: hidden;
	margin-top: 20rpx;
}

.img-size {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

</style>